import webaseHttp from "@/utils/webaseHttp";

let contractAddress = "0x661ed6a5ad37ca2bad522675190b68e7f06c74c8";
let user = "0xb8506457582e550f5b173fa70d6d5f63f6fc62ad"; 

/**
 * 创建质量记录
 * @param {Object} params 包含产品质量信息的对象
 * @returns {Promise} API调用结果
 */
export function createQualityRecord(params) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "createQualityRecord",
        "funcParam": [
            params.productId,
            params.traceCode,
            params.productName,
            params.origin,
            params.harvestTime,
            params.minTemp,
            params.maxTemp
        ],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "productId", "type": "uint256", "value": params.productId},
                {"name": "traceCode", "type": "string", "value": params.traceCode},
                {"name": "productName", "type": "string", "value": params.productName},
                {"name": "origin", "type": "string", "value": params.origin},
                {"name": "harvestTime", "type": "uint256", "value": params.harvestTime},
                {"name": "minTemp", "type": "int256", "value": params.minTemp},
                {"name": "maxTemp", "type": "int256", "value": params.maxTemp}
            ],
            "name": "createQualityRecord",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 手动认证产品质量
 * @param {BigInteger} productId 产品ID
 * @param {Number} auditStatus 审核状态 (0: 等待审核, 1: 通过, 2: 失败)
 * @param {String} auditComment 审核意见
 * @returns {Promise} API调用结果
 */
export function manualCertify(productId, auditStatus, auditComment) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "manualCertify",
        "funcParam": [productId, auditStatus, auditComment],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "productId", "type": "uint256", "value": productId},
                {"name": "auditStatus", "type": "uint8", "value": auditStatus},
                {"name": "auditComment", "type": "string", "value": auditComment}
            ],
            "name": "manualCertify",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 获取物流监控合约地址
 * @returns {Promise} 物流监控合约地址
 */
export function getLogisticsMonitor() {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "logisticsMonitor",
        "funcParam": [],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [],
            "name": "logisticsMonitor",
            "outputs": [{"name": "", "type": "address"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 添加授权用户
 * @param {String} userAddress 用户地址
 * @returns {Promise} API调用结果
 */
export function addAuthorizedUser(userAddress) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "addAuthorizedUser",
        "funcParam": [userAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "user", "type": "address", "value": userAddress}
            ],
            "name": "addAuthorizedUser",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 检查用户是否授权
 * @param {String} userAddress 用户地址
 * @returns {Promise} 是否授权
 */
export function checkAuthorizedUser(userAddress) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "authorizedUsers",
        "funcParam": [userAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "", "type": "address", "value": userAddress}],
            "name": "authorizedUsers",
            "outputs": [{"name": "", "type": "bool"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 自动认证产品
 * @param {String} orderId 订单ID
 * @returns {Promise} 认证结果
 */
export function autoCertify(orderId) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "autoCertify",
        "funcParam": [orderId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "orderId", "type": "string", "value": orderId}
            ],
            "name": "autoCertify",
            "outputs": [{"name": "", "type": "bool"}],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 通过溯源码获取产品ID
 * @param {String} traceCode 溯源码
 * @returns {Promise} 产品ID
 */
export function getProductIdByTraceCode(traceCode) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getProductIdByTraceCode",
        "funcParam": [traceCode],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "traceCode", "type": "string", "value": traceCode}],
            "name": "getProductIdByTraceCode",
            "outputs": [{"name": "", "type": "uint256"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 关联运输记录
 * @param {Number} productId 产品ID
 * @param {Number} transportId 运输ID
 * @returns {Promise} API调用结果
 */
export function linkTransport(productId, transportId) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "linkTransport",
        "funcParam": [productId, transportId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "productId", "type": "uint256", "value": productId},
                {"name": "transportId", "type": "uint256", "value": transportId}
            ],
            "name": "linkTransport",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 移除授权用户
 * @param {String} userAddress 用户地址
 * @returns {Promise} API调用结果
 */
export function removeAuthorizedUser(userAddress) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "removeAuthorizedUser",
        "funcParam": [userAddress],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "user", "type": "address", "value": userAddress}
            ],
            "name": "removeAuthorizedUser",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam).then(res => {
        return res;
    });
}

/**
 * 获取合约拥有者地址
 * @returns {Promise} 拥有者地址
 */
export function getOwner() {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "owner",
        "funcParam": [],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [],
            "name": "owner",
            "outputs": [{"name": "", "type": "address"}],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        return res;
    });
}

/**
 * 通过溯源码获取质量记录信息
 * @param {String} traceCode 溯源码
 * @returns {Promise} 质量记录信息
 */
export function getQualityByTraceCode(traceCode) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "getQualityByTraceCode",
        "funcParam": [traceCode],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "traceCode", "type": "string", "value": traceCode}],
            "name": "getQualityByTraceCode",
            "outputs": [
                {"name": "", "type": "uint256"},
                {"name": "", "type": "string"},
                {"name": "", "type": "string"},
                {"name": "", "type": "string"},
                {"name": "", "type": "uint256"},
                {"name": "", "type": "int256"},
                {"name": "", "type": "int256"},
                {"name": "", "type": "uint256"},
                {"name": "", "type": "uint256"},
                {"name": "", "type": "bool"},
                {"name": "", "type": "uint8"},
                {"name": "", "type": "string"},
                {"name": "", "type": "uint256"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        // 解析返回结果，将数组转换为对象
        if (Array.isArray(res)) {
            return {
                productId: res[0],
                traceCode: res[1],
                productName: res[2],
                origin: res[3],
                harvestTime: res[4],
                minTemp: res[5],
                maxTemp: res[6],
                transportId: res[7],
                transportScore: res[8],
                temperatureSafe: res[9],
                auditStatus: res[10],
                auditComment: res[11],
                certifyTime: res[12]
            };
        }
        return res;
    });
}

/**
 * 根据产品ID获取质量记录信息
 * @param {Number} productId 产品ID
 * @returns {Promise} 质量记录信息
 */
export function getQualityRecord(productId) {
    let params = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "qualityRecords",
        "funcParam": [productId],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [{"name": "", "type": "uint256", "value": productId}],
            "name": "qualityRecords",
            "outputs": [
                {"name": "productId", "type": "uint256"},
                {"name": "traceCode", "type": "string"},
                {"name": "productName", "type": "string"},
                {"name": "origin", "type": "string"},
                {"name": "harvestTime", "type": "uint256"},
                {"name": "minTemp", "type": "int256"},
                {"name": "maxTemp", "type": "int256"},
                {"name": "transportId", "type": "uint256"},
                {"name": "transportScore", "type": "uint256"},
                {"name": "temperatureSafe", "type": "bool"},
                {"name": "auditStatus", "type": "uint8"},
                {"name": "auditComment", "type": "string"},
                {"name": "certifyTime", "type": "uint256"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    };
    return webaseHttp.post('/', params).then(res => {
        // 解析返回结果，将数组转换为对象
        if (Array.isArray(res)) {
            return {
                productId: res[0],
                traceCode: res[1],
                productName: res[2],
                origin: res[3],
                harvestTime: res[4],
                minTemp: res[5],
                maxTemp: res[6],
                transportId: res[7],
                transportScore: res[8],
                temperatureSafe: res[9],
                auditStatus: res[10],
                auditComment: res[11],
                certifyTime: res[12]
            };
        }
        return res;
    });
}

/**
 * 辅助函数: 格式化时间戳为日期
 * @param {Number} timestamp 时间戳(秒)
 * @returns {String} 格式化的日期
 */
export function formatTimestamp(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    return date.toLocaleString();
}

/**
 * 辅助函数: 获取审核状态文本
 * @param {Number} status 审核状态码
 * @returns {String} 状态文本
 */
export function getAuditStatusText(status) {
    switch (parseInt(status)) {
        case 0: return '等待审核';
        case 1: return '通过验证';
        case 2: return '验证失败';
        default: return '未知状态';
    }
}

/**
 * 提交温度记录
 * @param {String} traceCode 溯源码
 * @param {Number} temperature 温度值
 * @param {Number} timestamp 记录时间戳
 * @returns {Promise} API调用结果
 */
export function submitTemperatureRecord(traceCode, temperature, timestamp) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "submitTemperatureRecord",
        "funcParam": [traceCode, temperature, timestamp],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": false,
            "inputs": [
                {"name": "traceCode", "type": "string", "value": traceCode},
                {"name": "temperature", "type": "int256", "value": temperature},
                {"name": "timestamp", "type": "uint256", "value": timestamp}
            ],
            "name": "submitTemperatureRecord",
            "outputs": [{"name": "", "type": "bool"}],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam);
}

/**
 * 检查产品质量状态
 * @param {String} traceCode 溯源码
 * @returns {Promise} API调用结果
 */
export function checkQualityStatus(traceCode) {
    let pam = {
        "groupId": "1",
        "user": user,
        "contractName": "QualityCertifier",
        "contractPath": "com.liannong",
        "version": "",
        "funcName": "checkQualityStatus",
        "funcParam": [traceCode],
        "contractAddress": contractAddress,
        "contractAbi": [{
            "constant": true,
            "inputs": [
                {"name": "traceCode", "type": "string", "value": traceCode}
            ],
            "name": "checkQualityStatus",
            "outputs": [
                {"name": "isQualified", "type": "bool"},
                {"name": "minRecordedTemp", "type": "int256"},
                {"name": "maxRecordedTemp", "type": "int256"},
                {"name": "lastCheckTime", "type": "uint256"}
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        }],
        "useAes": false,
        "useCns": false,
        "cnsName": ""
    }
    return webaseHttp.post('/', pam);
}